package user

import (
	"ChatServerDemo/protocol"
	"encoding/json"
	"net"
	"time"
)

type User struct {
	Name string
	Conn net.Conn
	JoinTime int64
}

func NewUser(conn net.Conn, name string) *User {
	local := &User{Name:name, Conn:conn, JoinTime:time.Now().Unix()}
	return local
}

func (slf *User) Kick() {

	message := protocol.Quit{
		Nick:    slf.Name,
	}
	slf.SendClient("Quit",message)
}

func (slf *User) SendClient(cmd string, msg interface{}) {
	jsonMsg, _ := json.Marshal(msg)
	packet := protocol.TCPPacket{
		Cmd:    cmd,
		Packet: string(jsonMsg),
		Timestamp:  time.Now().Unix(),
	}
	pkg, _ := json.Marshal(packet)
	slf.Conn.Write(pkg)
}

func (slf *User) SendClientMsgAll(m []string) {

	message := protocol.ReceiveMsgList{MsgList:[]protocol.ReceiveMsg{}}
	for _,v :=range m{
		packet := protocol.ReceiveMsg{}
		err := json.Unmarshal([]byte(v), &packet)
		if err != nil {
			return
		}
		message.MsgList = append(message.MsgList, packet)
	}
	slf.SendClient("ReceiveMsgList" ,message)
}